package com.sptpc.book.service;

import com.sptpc.book.model.Category;
import com.sptpc.book.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CategoryService {
    @Autowired
    private CategoryRepository categoryRepository;


    public Category saveCategory(Category category) {
        return categoryRepository.save(category);
    }

    public List<Category> findAll() {
        return categoryRepository.findAll(Sort.by(Sort.Direction.ASC, "id"));
    }

    public Category findOne(String name) {
        Optional<Category> category = categoryRepository.findCategoriesByNameLike(name);
        if (category.isPresent()) {
            return category.get();
        } else {
            return null;
        }
    }

    public Category findOne(Long id) {
        Optional<Category> category = categoryRepository.findById(id);
        if (category.isPresent()) {
            return category.get();
        } else {
            return null;
        }
    }
}
